//
//  HRuserAccount.swift
//  微博
//
//  Created by 众力金融 on 2017/1/13.
//  Copyright © 2017年 众力金融. All rights reserved.
//

import UIKit

fileprivate let accountFile: NSString = "useraccount.json"
//用户账户信息
class HRuserAccount: NSObject {

    //访问令牌
    var access_token: String?
    //用户id
    var uid: String?
    //过期日期 单位秒数
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    //过期日期
    var expiresDate: Date?
    
    //用户昵称
    var screen_name: String?
    //用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    
    override var description: String {
        return yy_modelDescription()
    }
    
   override init() {
        super.init()
    //从磁盘加载保存的文件 -> 字典
    guard let path = accountFile.cz_appendDocumentDir(),
          let data = NSData(contentsOfFile: path),
          let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject]
    else {
        return
    }
    
    //使用字典设置属性值
    //*****用户是否登录的关键代码
    yy_modelSet(with: dict ?? [:])
    
    //判断token是否过期
    //测试过期日期
//    expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
//    print(expiresDate as Any)
    if expiresDate?.compare(Date()) != .orderedDescending {
        print("账户过期")
        access_token = nil
        uid = nil
        //删除账户文件
       try? FileManager.default.removeItem(atPath: path)
    }
     print("账户正常")
    }
    
      /**
       1.偏好设置(小) -
       2.沙盒-归档/plist/josn
       3.数据库
       4.钥匙串访问(小/自动加密/需要使用框架 SSKeychain)
       */
    
    func saveAccount() {
         //1.模型转字典
         var dict = (self.yy_modelToJSONObject() as? [String: AnyObject]) ?? [:]
         //需要删除 expires_inz值
         dict.removeValue(forKey: "expires_in")
         //2.字典序列化data
        
         guard  let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
                 let fileName = accountFile.cz_appendDocumentDir()
        else {
            return
        }
        
       
         //3.写入磁盘
         (data as NSData).write(toFile: fileName, atomically: true)
        print("用户数据保存路径 \(fileName)")
        
    }
}
